<template>
  <div class="reports-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>财务报表</h1>
        <p>查看台球厅营收和财务数据</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="exportReport">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 时间筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>

        <el-form-item label="快捷选择">
          <el-button-group>
            <el-button @click="setDateRange('today')">今日</el-button>
            <el-button @click="setDateRange('week')">本周</el-button>
            <el-button @click="setDateRange('month')">本月</el-button>
            <el-button @click="setDateRange('year')">本年</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 财务概览 -->
    <div class="stats-row">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon revenue">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">¥{{ financialStats.totalRevenue }}</div>
            <div class="stat-label">总营收</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon orders">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ financialStats.totalOrders }}</div>
            <div class="stat-label">订单数量</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon avg">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">¥{{ financialStats.avgOrderValue }}</div>
            <div class="stat-label">平均订单金额</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon hours">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ financialStats.totalHours }}</div>
            <div class="stat-label">总使用时长(小时)</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 收入趋势图 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>收入趋势</span>
        </div>
      </template>
      <div class="chart-container">
        <v-chart
          :option="revenueChartOption"
          :style="{ height: '300px', width: '100%' }"
          autoresize
        />
      </div>
    </el-card>

    <!-- 台球桌使用率 -->
    <div class="usage-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>台球桌使用率分布</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart
                :option="usageRateChartOption"
                :style="{ height: '300px', width: '100%' }"
                autoresize
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>台球桌营收对比</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart
                :option="tableRevenueChartOption"
                :style="{ height: '300px', width: '100%' }"
                autoresize
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-card class="chart-card" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>台球桌详细数据</span>
          </div>
        </template>
        <el-table :data="tableUsageData" style="width: 100%">
          <el-table-column prop="tableName" label="台球桌" width="120" />
          <el-table-column prop="totalHours" label="使用时长(小时)" width="150" />
          <el-table-column prop="revenue" label="营收" width="120">
            <template #default="scope">
              ¥{{ scope.row.revenue }}
            </template>
          </el-table-column>
          <el-table-column prop="usageRate" label="使用率" width="120">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.usageRate"
                :color="getUsageRateColor(scope.row.usageRate)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="orderCount" label="订单数" width="100" />
          <el-table-column prop="avgDuration" label="平均时长" width="120" />
        </el-table>
      </el-card>
    </div>

    <!-- 收入明细 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>收入明细</span>
          <el-button link @click="viewAllOrders">查看全部订单</el-button>
        </div>
      </template>
      <el-table :data="revenueDetails" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="orderCount" label="订单数" width="100" />
        <el-table-column prop="revenue" label="营收" width="120">
          <template #default="scope">
            ¥{{ scope.row.revenue }}
          </template>
        </el-table-column>
        <el-table-column prop="hours" label="使用时长" width="120" />
        <el-table-column prop="avgOrderValue" label="平均订单金额" width="150">
          <template #default="scope">
            ¥{{ scope.row.avgOrderValue }}
          </template>
        </el-table-column>
        <el-table-column label="趋势" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.trend === 'up' ? 'success' : scope.row.trend === 'down' ? 'danger' : 'info'"
            >
              {{ getTrendText(scope.row.trend) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Download,
  Refresh,
  Money,
  Document,
  TrendCharts,
  Clock
} from '@element-plus/icons-vue';
import {
  getFinanceOverview,
  getRevenueTrend,
  getTableAnalysis,
  getHourlyAnalysis,
  getMonthlyComparison
} from '../../api/finance';

export default {
  name: 'Reports',
  components: {
    Download,
    Refresh,
    Money,
    Document,
    TrendCharts,
    Clock
  },
  setup() {
    const loading = ref(false);

    // 筛选表单
    const filterForm = reactive({
      dateRange: []
    });

    // 财务数据
    const financialData = ref([]);
    const tableUsageData = ref([]);
    const revenueDetails = ref([]);
    const overviewData = ref({
      totalRevenue: 0,
      todayRevenue: 0,
      monthRevenue: 0,
      totalOrders: 0,
      todayOrders: 0,
      averageOrderAmount: 0,
      totalUsageHours: 0
    });

    // 计算属性
    const financialStats = computed(() => {
      return {
        totalRevenue: overviewData.value.totalRevenue.toFixed(2),
        totalOrders: overviewData.value.totalOrders,
        totalHours: overviewData.value.totalUsageHours.toFixed(1),
        avgOrderValue: overviewData.value.averageOrderAmount.toFixed(2)
      };
    });

    // 收入趋势图配置
    const revenueChartOption = computed(() => ({
      title: {
        text: '收入趋势',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>收入: ¥{c}'
      },
      xAxis: {
        type: 'category',
        data: financialData.value.map(item => item.date.substring(5))
      },
      yAxis: {
        type: 'value',
        name: '收入(元)',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        data: financialData.value.map(item => item.revenue),
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(64, 158, 255, 0.1)'
            }]
          }
        }
      }]
    }));

    // 台球桌使用率饼图配置
    const usageRateChartOption = computed(() => ({
      title: {
        text: '使用率分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}% ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        name: '使用率',
        type: 'pie',
        radius: '50%',
        data: tableUsageData.value.map(item => ({
          value: item.usageRate,
          name: item.tableName
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }));

    // 台球桌营收柱状图配置
    const tableRevenueChartOption = computed(() => ({
      title: {
        text: '营收对比',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>营收: ¥{c}'
      },
      xAxis: {
        type: 'category',
        data: tableUsageData.value.map(item => item.tableName),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '营收(元)',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        data: tableUsageData.value.map(item => item.revenue),
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#67c23a'
            }, {
              offset: 1, color: '#85ce61'
            }]
          }
        }
      }]
    }));

    // 方法
    const loadFinancialData = async () => {
      try {
        loading.value = true;

        // 加载财务概览
        await loadOverview();

        // 加载收入趋势
        await loadRevenueTrend();

        // 加载台球桌分析
        await loadTableAnalysis();

      } catch (error) {
        console.error('加载财务数据失败:', error);
        ElMessage.error('加载财务数据失败');
      } finally {
        loading.value = false;
      }
    };

    const loadOverview = async () => {
      try {
        const response = await getFinanceOverview();
        if (response.success) {
          const data = response.data;
          overviewData.value = {
            totalRevenue: parseFloat(data.revenue?.total || 0),
            todayRevenue: parseFloat(data.revenue?.today || 0),
            monthRevenue: parseFloat(data.revenue?.month || 0),
            totalOrders: data.orders?.total || 0,
            todayOrders: data.orders?.today || 0,
            averageOrderAmount: parseFloat(data.orders?.avg_amount || 0),
            totalUsageHours: parseFloat(data.orders?.total_hours || 0)
          };
        } else {
          ElMessage.error(response.message || '加载财务概览失败');
        }
      } catch (error) {
        console.error('加载财务概览失败:', error);
        ElMessage.error('加载财务概览失败');
      }
    };

    const loadRevenueTrend = async () => {
      try {
        const response = await getRevenueTrend(30);
        if (response.success) {
          const trendData = response.data.trend || response.data;
          financialData.value = trendData.map(item => ({
            date: item.date,
            revenue: parseFloat(item.revenue || 0),
            orderCount: item.order_count || item.orders || 0,
            hours: parseFloat(item.total_hours || 0)
          }));

          // 生成收入明细
          revenueDetails.value = trendData.map((item, index, arr) => {
            const prevRevenue = index > 0 ? parseFloat(arr[index - 1].revenue || 0) : parseFloat(item.revenue || 0);
            const currentRevenue = parseFloat(item.revenue || 0);
            let trend = 'stable';
            if (currentRevenue > prevRevenue) trend = 'up';
            else if (currentRevenue < prevRevenue) trend = 'down';

            const orderCount = item.order_count || item.orders || 0;
            return {
              date: item.date,
              orderCount,
              revenue: currentRevenue,
              hours: parseFloat(item.total_hours || 0),
              avgOrderValue: orderCount > 0 ? (currentRevenue / orderCount).toFixed(2) : 0,
              trend
            };
          });
        } else {
          ElMessage.error(response.message || '加载收入趋势失败');
        }
      } catch (error) {
        console.error('加载收入趋势失败:', error);
        ElMessage.error('加载收入趋势失败');
      }
    };

    const loadTableAnalysis = async () => {
      try {
        const response = await getTableAnalysis();
        if (response.success) {
          const analysisData = response.data.analysis || response.data;
          tableUsageData.value = analysisData.map(item => ({
            tableName: item.name || item.table_name,
            totalHours: parseFloat(item.total_hours || 0),
            revenue: parseFloat(item.total_revenue || 0),
            usageRate: Math.min(100, Math.round(parseFloat(item.utilization_rate || 0))),
            orderCount: item.order_count || 0,
            avgDuration: item.order_count > 0 ? (parseFloat(item.total_hours || 0) / item.order_count).toFixed(1) : 0
          }));
        } else {
          ElMessage.error(response.message || '加载台球桌分析失败');
        }
      } catch (error) {
        console.error('加载台球桌分析失败:', error);
        ElMessage.error('加载台球桌分析失败');
      }
    };

    const refreshData = async () => {
      await loadFinancialData();
      ElMessage.success('数据刷新成功');
    };

    const exportReport = () => {
      ElMessage.success('报表导出功能开发中...');
    };

    const handleDateChange = async () => {
      // 根据日期范围重新加载数据
      await loadFinancialData();
    };

    const setDateRange = (type) => {
      const today = new Date();
      const formatDate = (date) => date.toISOString().split('T')[0];

      switch (type) {
        case 'today':
          filterForm.dateRange = [formatDate(today), formatDate(today)];
          break;
        case 'week':
          const weekStart = new Date(today.setDate(today.getDate() - today.getDay()));
          const weekEnd = new Date(today.setDate(weekStart.getDate() + 6));
          filterForm.dateRange = [formatDate(weekStart), formatDate(weekEnd)];
          break;
        case 'month':
          const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
          const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
          filterForm.dateRange = [formatDate(monthStart), formatDate(monthEnd)];
          break;
        case 'year':
          const yearStart = new Date(today.getFullYear(), 0, 1);
          const yearEnd = new Date(today.getFullYear(), 11, 31);
          filterForm.dateRange = [formatDate(yearStart), formatDate(yearEnd)];
          break;
      }
      handleDateChange();
    };

    const getUsageRateColor = (rate) => {
      if (rate >= 80) return '#67c23a';
      if (rate >= 60) return '#e6a23c';
      return '#f56c6c';
    };

    const getTrendText = (trend) => {
      const trendMap = {
        up: '上升',
        down: '下降',
        stable: '稳定'
      };
      return trendMap[trend] || '稳定';
    };

    const viewAllOrders = () => {
      ElMessage.info('跳转到订单管理页面...');
    };

    onMounted(() => {
      // 默认设置为本月
      setDateRange('month');
    });

    return {
      loading,
      filterForm,
      financialData,
      tableUsageData,
      revenueDetails,
      financialStats,
      revenueChartOption,
      usageRateChartOption,
      tableRevenueChartOption,
      refreshData,
      exportReport,
      handleDateChange,
      setDateRange,
      getUsageRateColor,
      getTrendText,
      viewAllOrders
    };
  }
};
</script>

<style scoped>
.reports-container {
  padding: 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #2c3e50;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 筛选卡片 */
.filter-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 12px;
}

/* 统计卡片 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stat-icon.avg {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-icon.hours {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

/* 图表卡片 */
.chart-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 12px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.usage-section {
  margin-bottom: 20px;
}

/* 表格卡片 */
.table-card {
  border: none;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .reports-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: flex-start;
  }

  .stats-row {
    grid-template-columns: 1fr;
  }
}
</style>
